<?php

class UploadController extends Controller {

	public function filters()
	{
		return array(
				'accessControl', // perform access control for CRUD operations
		);
	}
	
	
	public function accessRules()
	{
		return array(
				array('allow',  // allow all users to perform 'index' and 'view' actions
						'actions'=>array('index', 'addpub', 'upload'),
						'users'=>array('@'),
				),
				array('deny',  // deny all users
						'users'=>array('*')
				)
		);
	}
	
	public function actionIndex() {
		
		//用户可用项目列表
		$projects= Project::model()->findAll(array(
				'with'=>array('users'),
				'condition'=>'users.userId = ?',
				'params'=>array(Yii::app()->user->userId)
		));	//用户可用项目
		
		if (count($projects)<=0) {
			throw new CHttpException('403', '你暂时没有被分配项目');
			exit;
		}
		
		$projectListData = CHtml::listData($projects,'projectId','projectName');

		$defaultProjectId = Yii::app()->user->defaultProject;
		if ($defaultProjectId==0) $defaultProjectId = $projects[0]->projectId;
		$currentProjectId = Yii::app()->request->getParam('id', '0');
		$currentProjectId = $currentProjectId=='0' ? $defaultProjectId : $currentProjectId;	//当前项目id
		$currentProject = Project::model()->findByPk($currentProjectId);
		
		if (is_null($currentProject)) {
			throw new CHttpException('500', '无此项目');
		}
		
		//获得项目可用测试上传主机
		$hosts = Host::model()->findAll(array(
				'condition'=>'hostType=0',
				'with'=>array(
						'projects'=>array(
								'condition'=>'projects.projectId='. $currentProjectId,
						),
						'users'=>array(
								'condition'=>'users.userId='. Yii::app()->user->userId
						)
				),
		));
		$hostListData = CHtml::listData($hosts,'hostId','hostText');
		
		if (count($hosts)<=0) {
			throw new CHttpException('403', '此项目你暂时没有被分配发布主机');
		}
		
		
		$model=new Upload('search');
		$model->unsetAttributes();  // clear any default values
		
		if(isset($_GET['Upload']))
			$model->attributes=$_GET['Upload'];
		
		$this->render('index',array(
				'model'=>$model,  //upload model
				'projects'=>$projects,
				'currentProject'=>$currentProject,
				'hostListData'=>$hostListData
		));
		
		
	}

     /**
     * 添加到发布列表
     */
    public function actionAddpub() {
        $return = array();
        $uploadIds = $_POST['uploadIds'];
        $projectId = $_POST['projectId'];
		$rows = Yii::app()->db->createCommand()->from('{{upload}}')
					->where('uploadId in ('. $uploadIds .')')
					->queryAll();
        if (count($rows)>0) {
            $sql = "REPLACE INTO {{pub}} (filename,author,updateTime,projectId,isPub,status,logMessage,timezone) VALUES ";
            foreach($rows as $row) {
            	if ($row['isUpload']==0) {
            		Tools::ajaxErrorReturn('你选择的文件中有未上传的文件，请上传测试后再放入发布列表');
            	}
                $sql .=' ("'. $row['filename'] .'", "'. $row['author'] .'", "'. $row['updateTime'] .'", '. $projectId .', 0, "'. $row['status'] .'", "'. $row['logMessage'].'","'. $row['timezone'] .'" ),';
            }
            $sql = trim($sql, ",");
            $ret = Yii::app()->db->createCommand($sql)->execute();

            if (!$ret) {
                $return['error'] = '放入失败，可能数据库异常';
            }
        }
        echo CJSON::encode($return);
        exit;
    }

    /**
     * 加入标签
     * @author yanxiaowei
     */

    public function actionTag() {
        $return = array();

        $project_id = $_POST['project_id'];
        $update_ids_arr = explode(',', $_POST['update_ids']);
        $optype = $_POST['optype'];

        if($optype == 'editTag') {
            // 已有标签
            $tag_id = $_POST['tag_id'];

            $sql = "select filename from `upload` where upload_id in (". $_POST['update_ids'] .")
                        and project_id = {$project_id}";
            $ret = Yii::app()->db->createCommand($sql)->queryAll(true);
            if(count($ret) > 0) {
                // 拼凑sql
                $tmpSql = '';
                foreach($ret as $v) {
                    $sql2 = "SELECT * FROM `tag_file` WHERE tag_id = {$tag_id} and project_id = {$project_id}
                        and filename = '{$v['filename']}'";
                    $ret2 = Yii::app()->db->createCommand($sql2)->queryAll(true);
                    if(count($ret2) > 0) {
                        // 已经在标签文件表中了
                        continue;
                    }
                    else {
                        $tmpSql .= " ({$tag_id}, {$project_id}, '{$v['filename']}'),";
                    }
                }
                $tmpSql = trim($tmpSql, ",");
                if ($tmpSql == '') {
                    // 所有文件已经在标签列表中
                    $return['error'] = '所选文件已经在标签列表中!';
                }
                else {
                    $sql3 = "INSERT INTO `tag_file`(tag_id, project_id, filename) VALUES ".$tmpSql;
                    if (!Yii::app()->db->createCommand($sql3)->execute()) {
                        $return['error'] = '失败';
                    }
                }
            }
            else {
                // 上传表中无数据
                $return['error'] = '失败';
            }
            echo CJSON::encode($return);
            exit;
        }
        elseif ($optype == 'addTag') {
            // 新增标签
            // 添加标签
            $tag1 = new Tag();
            $tag1->name = $_POST['tag_name'];
            $tag1->creator = Yii::app()->user->id;
            $tag1->remark = $_POST['remark'];
            $ret = $tag1->save();
            if($ret !== true) {
                $return['error'] = '添加标签失败';
            }
            else {
                // 读取新添加标签的自增主键
                $tag_id = $tag1->attributes['tag_id'];

                // 读取提交文件
                $sql = "select * from `upload` where upload_id in (". $_POST['update_ids'] .")";
                $ret = Yii::app()->db->createCommand($sql)->queryAll(true);
                if(count($ret) > 0) {
                    // 添加文件到标签列表文件中
                    $sql2 = "INSERT INTO `tag_file`(tag_id, project_id, filename) VALUES ";
                    foreach($ret as $v) {
                        $sql2 .= " ({$tag_id}, {$project_id}, '{$v['filename']}'),";
                    }

                    $sql2 = trim($sql2, ",");
                    if (!Yii::app()->db->createCommand($sql2)->execute()) {
                        $return['error'] = '失败';
                    }
                }
                else {
                    $return['error'] = '失败';
                }
            }
            echo CJSON::encode($return);
            exit;
        }
        else {
            $return['error'] = '无效的操作!';
            echo CJSON::encode($return);
            exit;
        }
    }

    public function actionUpload() {

    	$uploadIds = $_POST['uploadIds'];
    	$projectId = $_POST['projectId'];
    	$hostId = $_POST['hostId'];
    	
        $fileTag = date("YmdHis").rand(100,999);

        $host = Host::model()->findByPk($hostId);
        $project = Project::model()->findByPk($projectId);

        //svn获取
        $message = Tools::svnUpdate($project);
        if ($message!='') Tools::ajaxErrorReturn($message);

        //获得发布文件列表
        $files = Tools::getUploadFileList($uploadIds, $project);
        //打包
        $archive = "P".$projectId."_".$fileTag.".tar";
        $message = Tools::tar($archive, $files, $project);
        if ($message!='') Tools::ajaxErrorReturn($message);

        //发布文件
        $message = Tools::sendUpload($fileTag, $archive, $host, $project);
        if ($message!='') Tools::ajaxErrorReturn($message);
       
        Yii::app()->db->createCommand()->update('{{upload}}', array('isUpload'=>1), 
        							'uploadId IN ('. $uploadIds .')');
        
        @unlink(Yii::app()->params['archivesPath'].'/'.$archive);
        
        echo CJSON::encode(array());
        exit;
    }


}
